<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>原生node实现聊天室</title>
		<script src="http://localhost:3000/socket.io/socket.io.js"></script>
		<style type="text/css">
			.mine {color: red; font-weight: bold;}
		</style>
		<script>
			window.onload=function() {
				const sock=io.connect('ws://localhost:3000');
				const $=document.querySelector.bind(document);
				const btn_reg=$('#btn_reg');
				const btn_login=$('#btn_login');
				const btn_send=$('#btn_send');
				const username=$('#username');
				const password=$('#password');
				const text=$('#text');
				const uli=$('#uli');
				let cur_name=null;
				
				// 注册
				btn_reg.onclick=function() {
					sock.emit('reg', username.value, password.value);
				};
				sock.on('reg_res', (code, message)=>{
					if(code) {
						alert(`注册失败, ${message}`)
					} else {
						alert('注册成功');
					}
				});
				
				// 登录
				btn_login.onclick=function() {
					sock.emit('login', username.value, password.value);
				};
				sock.on('login_res', (code, message)=>{
					if(code) {
						alert(`登录失败, ${message}`)
					} else {
						cur_name=username.value;
						alert('登录成功');
					}
				});
				
				// 发送消息
				btn_send.onclick=function() {
					if(text.value.trim()) {
						sock.emit('send', cur_name, text.value);
					} else {
						alert('发送的消息不能为空');
					}
				};
				sock.on('send_res', (code, massage)=>{
					if(code) {
						alert(`消息发送失败:${message}`);
					} else {
						let li=document.createElement('li');
						li.innerHTML=`${cur_name}: ${text.value}`;
						li.className='mine';
						uli.appendChild(li);
					}
				})
				
				sock.on('send', (name, message)=>{
					let li=document.createElement('li');
					li.innerHTML=`${name}: ${message}`;
					uli.appendChild(li);
				});
				
			};
		</script>
	</head>
	<body>
		<label for="username">用户名
			<input type="text" id="username">
		</label>
		<label for="password">密码
			<input type="password" id="password">
		</label>
		<button id="btn_reg">注册</button>
		<button id="btn_login">登录</button>
		<hr>
		<div class="message_container">
			<ul id="uli">
			</ul>
		</div>
		
		
		<div class="send_message">
			<textarea id="text" rows="8" cols="100" style="resize: none;"></textarea>
			<button id="btn_send">发送</button>
		</div>
	</body>
</html>
